package fr.utbm.gl52.smartgrid.model;

import java.lang.ref.WeakReference;
import java.util.UUID;

import fr.utbm.gl52.smartgrid.model.device.IDevice;
import fr.utbm.gl52.smartgrid.util.Constants;
import fr.utbm.gl52.smartgrid.util.PropertiesBuffer;
import fr.utbm.gl52.smartgrid.view.ViewManager;

public class ModelManager {
	private WeakReference<BusDC> model;
	private WeakReference<ViewManager> view;
	private IDevice temporarilyCreatedDevice;
	
	public void setModel(BusDC _model) {
		this.model = new WeakReference<BusDC>(_model);
	}

	public void setView(ViewManager _view) {
		this.view = new WeakReference<ViewManager>(_view);
	}

	private void sendDevices() // TODO private
	{
		this.view.get().update(this.model.get().getDeviceList());
	}

	private void sendDeviceInfo(IDevice device) {
		this.view.get().editRequest(device.getID(), device.getProperties());
	}

	/* ===== INPUT FROM CONTROLLER ===== */
	public void requestDevice(UUID uuid) {
		sendDeviceInfo(this.model.get().getDevice(uuid));
		this.temporarilyCreatedDevice = null;
	}

	public void addDevice(String className) {
		try {
			Class<?> cl = Class.forName(className);
			this.temporarilyCreatedDevice = (IDevice) cl.newInstance();
			this.view.get().setNewPropertyEditorPanel(
					this.temporarilyCreatedDevice.getID(),
					this.temporarilyCreatedDevice.getProperties());

		} catch (Exception e) {
			if (Constants.isDebug)
				System.out.println("error : class name : " + e.getMessage()); //$NON-NLS-1$
		}

	}

	public void removeDevice(UUID uuid) {
		this.model.get().getDeviceList().remove(uuid);
		sendDevices();
	}

	public void modifyDevice() {
		if (this.temporarilyCreatedDevice != null) {
			this.temporarilyCreatedDevice.setProperties(PropertiesBuffer
					.getProperties());
			this.model.get().addDevice(this.temporarilyCreatedDevice);
			this.temporarilyCreatedDevice = null;
		} else {
			this.model.get().getDevice(PropertiesBuffer.getDeviceID())
					.setProperties(PropertiesBuffer.getProperties());
		}
		sendDevices();
	}
}
